<template>
  <div class="app-container">
    <div class="head-container">
      <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增收费标准</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="standardList"
      border
      style="width: 100%"
    >
      <el-table-column type="index" width="200" label="序号" />
      <el-table-column prop="cartype" label="车辆类型" width="120">
        <template slot-scope="scope">
          <dict-tag :options="carTypeOptions" :value="scope.row.cartype" />
        </template>
      </el-table-column>
      <el-table-column prop="basecharge" label="基础费用(元)" width="120" />
      <el-table-column prop="overcharge" label="超时费用(元)" width="120" />
      <el-table-column prop="basetime" label="基础时长(分钟)" width="120" />
      <el-table-column prop="overtime" label="超时单位时长(分钟)" width="180" />
      <el-table-column label="操作" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑收费标准对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="车辆类型" prop="cartype">
          <el-select v-model="form.cartype" placeholder="请选择车辆类型">
            <el-option
              v-for="dict in carTypeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="基础费用" prop="basecharge">
          <el-input v-model.number="form.basecharge" placeholder="请输入基础费用" />
        </el-form-item>
        <el-form-item label="超时费用" prop="overcharge">
          <el-input v-model.number="form.overcharge" placeholder="请输入超时费用" />
        </el-form-item>
        <el-form-item label="基础时长" prop="basetime">
          <el-input v-model.number="form.basetime" placeholder="请输入基础时长(分钟)" />
        </el-form-item>
        <el-form-item label="超时单位时长" prop="overtime">
          <el-input v-model.number="form.overtime" placeholder="请输入超时单位时长(分钟)" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCstandard, addCstandard, updateCstandard, delCstandard } from '@/api/system/cstandard.js'
import DictTag from '@/components/DictTag'

export default {
  name: 'ChargingStandard',
  components: {
    DictTag
  },
  data() {
    return {
      loading: false,
      standardList: [],
      dialogVisible: false,
      dialogTitle: '',
      form: {},
      rules: {
        cartype: [
          { required: true, message: '请选择车辆类型', trigger: 'change' }
        ],
        basecharge: [
          { required: true, message: '请输入基础费用', trigger: 'blur' },
          { type: 'number', min: 0, message: '费用不能小于0', trigger: 'blur' }
        ],
        overcharge: [
          { required: true, message: '请输入超时费用', trigger: 'blur' },
          { type: 'number', min: 0, message: '费用不能小于0', trigger: 'blur' }
        ],
        basetime: [
          { required: true, message: '请输入基础时长', trigger: 'blur' },
          { type: 'number', min: 0, message: '时长不能小于0', trigger: 'blur' }
        ],
        overtime: [
          { required: true, message: '请输入超时单位时长', trigger: 'blur' },
          { type: 'number', min: 0, message: '时长不能小于0', trigger: 'blur' }
        ]
      },
      carTypeOptions: [
        { label: '小车', value: '小车' },
        { label: '中车', value: '中车' },
        { label: '大车', value: '大车' }
      ]
    }
  },
  created() {
    console.log('组件已创建，开始加载数据...')
    // 确保在DOM渲染完成后再获取数据，避免可能的时序问题
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      console.log('开始获取收费标准列表...')

      // 添加查询参数，确保获取的是未删除的数据
      const queryParams = {
        deleted: 0  // 只获取未删除的数据
      }

      console.log('API请求参数:', queryParams)

      // 直接调用API获取数据，不使用超时机制
      listCstandard(queryParams).then(response => {
        console.log('API完整响应:', response)
        console.log('API响应状态码:', response.code)
        console.log('API响应消息:', response.msg)
        console.log('API响应数据:', response.data)

        // 重置列表数据
        this.standardList = []

        // 正确处理后端返回的分页数据 - 考虑两种情况：数据在response中或者在response.data中
        if (response && response.code === 200) {
          // 记录返回的数据结构，便于调试
            console.log('响应数据结构:', {
              hasRows: !!response.rows,
              dataType: typeof response,
              total: response.total,
              rowsLength: response.rows ? response.rows.length : 0
            })

            let dataToProcess = []

            // 根据后端实际返回的格式处理数据 - 数据直接在response中
            if (response.rows && Array.isArray(response.rows)) {
              dataToProcess = response.rows
              console.log('发现rows数组，包含', dataToProcess.length, '条数据')
            } else if (Array.isArray(response)) {
              dataToProcess = response
              console.log('响应数据本身是数组，包含', dataToProcess.length, '条数据')
            } else {
              console.log('响应数据既不是标准分页结构也不是数组')
            }

          // 处理数据并添加默认值
            if (dataToProcess.length > 0) {
              this.standardList = dataToProcess.map((item, index) => {
                console.log(`处理第${index+1}条数据:`, item)
                return {
                  ...item,
                  basetime: item.basetime || 60,  // 如果后端没有返回basetime，设置默认值60分钟
                  overtime: item.overtime || 30   // 如果后端没有返回overtime，设置默认值30分钟
                }
              })
              console.log('成功处理了', this.standardList.length, '条收费标准数据')
              this.$message.success(`成功加载${this.standardList.length}条收费标准数据`)
            } else if (response && response.total > 0) {
              // 特殊情况：total > 0但没有rows数组
              console.log('发现有数据但格式不符合预期，总数:', response.total)
              this.$message.warning('数据格式异常，请联系管理员')
            } else {
              console.log('未获取到任何收费标准数据')
              this.$message.warning('未获取到收费标准数据')
            }

            console.log('最终显示的收费标准列表:', this.standardList)
          } else {
            console.log('未获取到有效数据或请求失败')
            console.log('响应状态码:', response ? response.code : 'undefined')
            this.$message.info('当前没有收费标准数据')
          }

        this.loading = false
      }).catch(error => {
        console.error('获取收费标准列表失败:', error)
        console.error('错误详情:', error.message, error.response)
        this.loading = false
        this.$message.error(`获取数据失败: ${error.message || '未知错误'}`)
      })
    },
    getCarTypeDict() {
      // 从字典API获取车辆类型数据
      // 由于实际API可能需要根据项目情况实现，这里先保留默认数据作为备用
      // 实际项目中应该调用真实的字典API
      // dictService.getDictData('sys_car_type').then(response => {
      //   this.carTypeOptions = response.data || [];
      // }).catch(error => {
      //   console.error('获取车辆类型字典失败:', error);
      //   // 发生错误时使用默认值
      //   this.setDefaultCarTypeOptions();
      // });

      // 暂时使用默认数据
      this.setDefaultCarTypeOptions();
    },

    // 设置默认车辆类型选项
    setDefaultCarTypeOptions() {
      this.carTypeOptions = [
        { label: '小车', value: '小车' },
        { label: '中车', value: '中车' },
        { label: '大车', value: '大车' }
      ]
    },
    handleAdd() {
      this.dialogTitle = '新增收费标准'
      this.reset()
      this.dialogVisible = true
    },
    handleUpdate(row) {
      this.dialogTitle = '编辑收费标准'
      // 复制行数据并确保使用正确的cid字段
      this.form = Object.assign({}, row)
      this.dialogVisible = true
    },
    handleDelete(row) {
      this.$confirm('确定要删除该收费标准吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 使用正确的删除API
        delCstandard(row.cid).then(response => {
          this.$message.success('删除成功')
          this.getList()
        }).catch(error => {
          console.error('删除收费标准失败:', error)
          this.$message.error('删除失败，请重试')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    reset() {
      this.form = {
        cartype: '',
        basecharge: 0,
        overcharge: 0,
        basetime: 60,
        overtime: 30,
        deleted: 0
      }
      // 只有当表单存在时才调用resetFields
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    cancel() {
      this.dialogVisible = false
      this.reset()
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 复制表单数据，提交所有必要字段
          const submitData = {
            cid: this.form.cid,
            cartype: this.form.cartype,
            basecharge: this.form.basecharge,
            overcharge: this.form.overcharge,
            basetime: this.form.basetime,
            overtime: this.form.overtime,
            deleted: this.form.deleted || 0
          }

          if (this.form.cid) {
            updateCstandard(submitData).then(response => {
              this.$message.success('修改成功')
              this.dialogVisible = false
              this.getList()
            }).catch(error => {
              console.error('修改收费标准失败:', error)
              this.$message.error('修改失败，请重试')
            })
          } else {
            // 检查是否已存在相同车辆类型的收费标准
            const isDuplicate = this.standardList.some(item => 
              item.cartype === this.form.cartype && !item.deleted
            )
            
            if (isDuplicate) {
              this.$message.warning('该车辆类型的收费标准已存在，不能重复添加')
              return
            }
            
            addCstandard(submitData).then(response => {
              this.$message.success('新增成功')
              this.dialogVisible = false
              this.getList()
            }).catch(error => {
              console.error('新增收费标准失败:', error)
              this.$message.error('新增失败，请重试')
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.head-container {
  margin-bottom: 20px;
}
</style>
